<template>
	<div class="wrap" v-loading="loading" element-loading-text="等下,我正在请求" element-loading-spinner="el-icon-loading">
		<basic-opt :has_left="false">
			<template #add>
				<div class="opt-item">
					<el-button @click="backApk" icon="el-icon-back" type="info" size="medium">
						返回</el-button>
				</div>
				<div class="opt-item">
					<el-button @click="addVersion" icon="el-icon-circle-plus-outline" type="primary" size="medium">
						添加固件版本</el-button>
				</div>
			</template>
		</basic-opt>

		<div class="table-box">
			<el-table :data="versionData" border stripe :header-cell-style="{background:'#f0f0f0', color: '#003366'}"
				max-height="620">
				<el-table-column prop="id" label="ID"></el-table-column>
				<el-table-column prop="apk_id" label="apk_id"></el-table-column>
				<el-table-column prop="version" label="版本"></el-table-column>
				<el-table-column prop="href" label="版本链接" width="500"></el-table-column>
				<el-table-column prop="created_at" label="创建日期"></el-table-column>
				<el-table-column fixed="right" label="操作" width="400">
					<template #default="scope">
						<el-button @click="releaseVersion(scope.row)" type="primary" plain size="mini">发布
						</el-button>
						<!-- <el-button @click="copyVersionLink(scope.row)" type="success" plain size="mini">复制链接
						</el-button> -->
						<el-button @click="viewVersionData(scope.row)" type="danger" plain size="mini">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<!-- <div class="m-pagination">
			<el-pagination :current-page="current" :page-sizes="[10, 20, 50, 100, 150, 200, 250, 300]" :page-size="size"
				layout="sizes, prev, pager, next, jumper" @current-change="currentChange" @size-change="sizeChange"
				:total="total">
			</el-pagination>
		</div> -->

		<!-- 添加固件版本 -->
		<el-drawer v-model="versionForm" :show-close="false" :before-close="closeVersionForm" size="40%">
			<template #title>
				<div class="u-drawer-title">
					<div>
						添加固件版本
					</div>
					<el-button type="danger" size="mini" plain @click="closeVersionForm">我不填了</el-button>
				</div>
			</template>
			<div class="m-form">
				<el-form ref="form" :model="form" label-width="120px">
					<div>
						<el-form-item label="版本号" prop="version">
							<el-input style="width: 300px;" v-model="form.version" placeholder="请输入版本名称"></el-input>
						</el-form-item>
						<el-form-item label="版本描述" prop="desc">
							<el-input style="width: 300px;" v-model="form.desc" type="textarea" placeholder="请输入版本描述">
							</el-input>
						</el-form-item>
						<el-form-item label="上传版本">
							<el-upload data="versionData" action="" :before-upload="beforeVersion"
								:on-exceed="onlyVersion" :on-success="successVersion" :on-progress="versionProcess"
								:on-remove="removeVersion" :limit="1" :auto-upload="false" ref="uploadVersion">
								<el-button size="small" plain type="primary" :disabled="isPercentage == true">选择包
								</el-button>
							</el-upload>
							<el-progress v-if="isPercentage == true" :text-inside="true" :stroke-width="15"
								:percentage="percentage"></el-progress>
							<el-button size="small" plain type="primary" @click="versionUpload"
								:disabled="isPercentage == true">已确认文件，立即上传</el-button>
						</el-form-item>
						<el-form-item label="版本链接" prop="href">
							<el-input style="width: 300px;" v-model="form.href" type="textarea"
								placeholder="此项版本上传完自动添加">
							</el-input>
						</el-form-item>
					</div>
					<div
						style="box-sizing: border-box; padding: 20px; position: absolute;bottom: 0; display: flex;justify-content: space-between;align-items: center;">
						<el-button style="width: 300px;" type="primary" @click="newVersion">提交</el-button>
						<el-button style="width: 300px;" type="primary" @click="resetVersion('form')">重置</el-button>
					</div>
				</el-form>
			</div>
		</el-drawer>

		<!-- 发布版本 -->
		<el-drawer v-model="releaseVersionForm" :show-close="false" :before-close="closeReleaseVersionForm" size="70%">
			<template #title>
				<div class="u-drawer-title">
					<div>
						发布版本
					</div>
					<el-button type="danger" size="mini" plain @click="closeReleaseVersionForm">我不填了</el-button>
				</div>
			</template>
			<div class="m-form">
				<el-form ref="releaseForm" :model="releaseForm" label-width="150px">
					<el-scrollbar height="90vh" v-loading="formLoading" element-loading-text="正在进行请求,请稍后"
						element-loading-spinner="el-icon-loading">
						<div class="form-flex">
							<el-form-item label="选择发布类型" prop="type">
								<el-select style="width: 300px;" v-model="releaseForm.type" placeholder="请选择发布类型"
									filterable @change="releaseTypeChange">
									<el-option v-for="(item,index) in releaseTypeList" :key="index" :label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</div>
						<div v-if="releaseForm.type == 2 || releaseForm.type == 3">
							<el-form-item label="选择项目">
								<project-component ref="childProject" :projectId="project_id"
									@getChildProjectId="getProjectId"></project-component>
							</el-form-item>
							<div v-if="(releaseForm.type == 2 || releaseForm.type == 3) && project_id != ''">
								<el-form-item label="选择地址(可多选)" prop="addresses">
									<address-component ref="childAddress" :projectId="project_id"
										:parentAddresses="releaseForm.addresses" @getChildAddresses="getAddresses">
									</address-component>
								</el-form-item>
							</div>
						</div>
						<div v-if="releaseForm.type == 3 && releaseForm.addresses.length > 0">
							<el-form-item label="选择方向">
								<direction-component :directionVal="direction_val"
									@getChildDirectionId="getDirectionId"></direction-component>
							</el-form-item>
							<div v-if="direction_val != ''">
								<el-form-item label="选择设备UUID" prop="uuid">
									<uuid-component :directionVal="direction_val"
										:parentAddresses="releaseForm.addresses" :parentUuid="releaseForm.uuid"
										@getChildUuid="getUuid"></uuid-component>
								</el-form-item>
							</div>
						</div>
						<div class="m-submit">
							<el-button class="u-submit-btn" type="primary" @click="newReleaseVersion">提交</el-button>
							<el-button class="u-submit-btn" type="info" @click="resetReleaseVersion('form')">重置
							</el-button>
						</div>
					</el-scrollbar>
				</el-form>
			</div>
		</el-drawer>


		<!-- 删除数据确认 -->
		<el-dialog title="删除数据" v-model="confirmVersionData" width="30%" :show-close="false">
			<el-descriptions class="margin-top" :column="1" :size="size" border>
				<el-descriptions-item>
					<template #label>
						id
					</template>
					{{delVersionData.id}}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						apk_id
					</template>
					{{delVersionData.apk_id}}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						版本
					</template>
					{{delVersionData.version}}
				</el-descriptions-item>
				<el-descriptions-item>
					<template #label>
						版本链接
					</template>
					<el-input type="textarea" rows="3" v-model="delVersionData.href"></el-input>
				</el-descriptions-item>
			</el-descriptions>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="confirmVersionData = false">取 消</el-button>
					<el-button type="primary" @click="confirmDelVersionData">确定删除</el-button>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script>
	import API from '@/api/index.js'
	import md5 from 'blueimp-md5'
	import COS from 'cos-js-sdk-v5'
	import ProjectComponent from '@/components/form/project-component.vue'
	import AddressComponent from '@/components/form/address-component.vue'
	import DirectionComponent from '@/components/form/direction-component.vue'
	import UuidComponent from '@/components/form/uuid-component.vue'


	export default {
		name: 'version',
		components: {
			ProjectComponent,
			AddressComponent,
			DirectionComponent,
			UuidComponent
		},
		data() {
			return {
				loading: false,
				apk_id: '', // 固件id
				versionData: [],
				confirmVersionData: false,
				delVersionData: {}, // 删除的数据
				// 分页
				current: 1, // 当前页
				size: 10, // 每页出现几条
				total: 0, // 总页数

				// 表单
				versionForm: false,
				form: {
					apk_id: '',
					version: '',
					desc: '',
					href: ''
				},

				// 上传
				suffix: '', // 后缀
				versionFile: '', // 文件内容
				versionName: '', // 文件名字
				versionFileName: '', // 加密后的文件名字
				uploadSign: null, // 获取的后台验证
				isPercentage: false,
				percentage: 0, // 进度条

				// 发布版本
				releaseVersionForm: false, // 显示表单
				formLoading: false,
				releaseForm: {
					version_id: '',
					type: '', // 1 all 2 addresses 3 uuid
					addresses: [],
					uuid: []
				},
				releaseTypeList: [{
					value: 1,
					label: '全部设备'
				}, {
					value: 2,
					label: '按地址选择'
				}, {
					value: 3,
					label: '自定义'
				}], // 发布类型
				project_id: '',
				// 设备方向
				direction_val: '',

			}
		},
		created() {

		},
		mounted() {
			this.apk_id = localStorage.getItem('apk_id');
			window.location.hash = "#/version?apk_id=" + this.apk_id;
			this.getVersion();
			this.getUploadToken();
		},
		methods: {
			backApk() {
				let self = this;
				localStorage.removeItem('apk_id');
				self.$router.replace('/package');
			},
			getVersion() {
				let self = this;
				self.loading = true;
				API.apkVersions(1, 10, self.apk_id).then(res => {
					let data = res.data.data;
					self.loading = false;
					self.versionData = data.data;
					self.total = data.total;
					self.current = 1;
				}).catch(err => {
					self.loading = false;
					self.$message.error(err.response.data.message)
				})
			},
			// 分页
			currentChange(val) {
				let self = this;
				self.loading = true;
				self.current = val;
				API.apkVersions(val, self.size, self.apk_id).then(res => {
					let data = res.data.data;
					self.loading = false;
					self.versionData = data.data;
					self.total = data.total;
				}).catch(err => {
					self.loading = false;
					self.$message.error(err.response.data.message)
				})
			},
			// 每页显示条数
			sizeChange(val) {
				let self = this;
				self.loading = true;
				self.size = val;
				API.apkVersions(self.current, val, self.apk_id).then(res => {
					let data = res.data.data;
					self.loading = false;
					self.versionData = data.data;
					self.total = data.total;
				}).catch(err => {
					self.loading = false;
					self.$message.error(err.response.data.message)
				})
			},
			// 编辑数据
			editVersionData(row) {
				let self = this;
				self.versionForm = true;
				self.form = {
					id: row.id,
					apk_id: row.apk_id,
					version: row.version,
					desc: row.desc,
					href: row.href
				}
			},
			// 查看删除数据
			viewVersionData(row) {
				let self = this;
				self.confirmVersionData = true;
				self.delVersionData = row;
			},
			// 确定删除数据
			confirmDelVersionData() {
				let self = this;
				self.confirmVersionData = false;
				console.log(self.delVersionData.id)
				API.delApkVersion(self.delVersionData.id).then(res => {
					console.log(res)
					self.$message.success("删除成功");
					self.getVersion();
					self.confirmVersionData = false;
				}).catch(err => {
					self.$message.error(err.response.data.message)
				});
			},
			// 添加固件
			addVersion() {
				let self = this;
				self.versionForm = true;
				self.isPercentage = false;
				self.form.apk_id = self.apk_id;
			},
			// 提交表单
			newVersion() {
				let self = this;
				self.$confirm('是否要提交信息？', '确认信息', {
						distinguishCancelAndClose: true,
						confirmButtonText: '确定提交',
						cancelButtonText: '不',
						showClose: false,
						closeOnClickModal: false
					})
					.then(() => {
						API.apkVersion(self.form).then(res => {
							console.log(res)
							self.$message.success("提交成功");
							self.getVersion();
							self.versionForm = false;
							self.form = {
								apk_id: '',
								version: '',
								desc: '',
								href: ''
							};
						}).catch(err => {
							self.$message.error(err.response.data.message)
						});
					})
					.catch(() => {});
			},
			// 关闭新增固件版本
			closeVersionForm() {
				let self = this;
				self.$confirm('是否要退出表单填写？', '确认信息', {
						distinguishCancelAndClose: true,
						confirmButtonText: '点错了,我还要填',
						cancelButtonText: '退出',
						showClose: false,
						closeOnClickModal: false
					})
					.then(() => {})
					.catch(() => {
						self.versionForm = false;
						self.form = {
							apk_id: '',
							version: '',
							desc: '',
							href: ''
						}
						self.$refs.uploadVersion.clearFiles();
					});
			},
			// 重置固件表单
			resetVersion(formName) {
				let self = this;
				self.$confirm('是否要重置表单？', '确认信息', {
						distinguishCancelAndClose: true,
						confirmButtonText: '确定重置',
						cancelButtonText: '点错了',
						showClose: false,
						closeOnClickModal: false
					})
					.then(() => {
						self.$refs[formName].resetFields();
						self.$refs.uploadVersion.clearFiles();
					})
					.catch(() => {});
			},
			// 选择发布类型
			releaseTypeChange(val) {
				let self = this;
				self.project_id = '';
				self.direction_val = '';
				self.releaseForm.addresses = [];
				self.releaseForm.uuid = [];
				switch (val) {
					case 1:
						self.releaseForm.type = 1;
						break;
					case 2:
						self.releaseForm.type = 2;
						break;
					case 3:
						self.releaseForm.type = 3;
				}
			},
			// 获取项目id
			getProjectId(data) {
				let self = this;
				self.project_id = data.child_project_id;
				// self.releaseForm.addresses = []; 
				self.direction_val = '';
				self.releaseForm.uuid = [];
			},
			// 地址组件项目id回传父组件,为了加载更多数据
			getAddressProjectId(data) {
				let self = this;
				self.project_id = data.project_id;
			},
			getAddresses(data) {
				let self = this;
				self.releaseForm.addresses = data.addresses;
				self.direction_val = '';
				self.releaseForm.uuid = [];
			},
			// 获取子组件方向id
			getDirectionId(data) {
				let self = this;
				self.direction_val = data.direction_val;
				self.releaseForm.uuid = [];
			},
			// 获取UUID
			getUuid(data) {
				let self = this;
				self.releaseForm.uuid = data.uuidList;
			},

			releaseVersion(row) {
				let self = this;
				self.releaseVersionForm = true;
				self.releaseForm.version_id = row.id;
			},
			// 发布提交
			newReleaseVersion() {
				let self = this;
				console.log(self.releaseForm);
				API.publishApk(self.releaseForm).then(res => {
					console.log(res)
					self.releaseVersionForm = false;
					self.$message.success("发布成功");
					self.releaseForm.type = '';
					self.project_id = '';
					self.direction_val = '';
					self.releaseForm.addresses = [];
					self.releaseForm.uuid = [];
				}).catch(err => {
					self.$message.error(err.response.data.message)
				})
			},
			// 关闭新增固件版本
			closeReleaseVersionForm() {
				let self = this;
				self.$confirm('是否要退出表单填写？', '确认信息', {
						distinguishCancelAndClose: true,
						confirmButtonText: '点错了,我还要填',
						cancelButtonText: '退出',
						showClose: false,
						closeOnClickModal: false
					})
					.then(() => {})
					.catch(() => {
						self.releaseForm.type = '';
						self.project_id = '';
						self.direction_val = '';
						self.releaseForm.addresses = [];
						self.releaseForm.uuid = [];
						self.releaseVersionForm = false;
					});
			},
			// 重置发布表单
			resetReleaseVersion(formName) {
				let self = this;
				self.$confirm('是否要重置表单？', '确认信息', {
						distinguishCancelAndClose: true,
						confirmButtonText: '确定重置',
						cancelButtonText: '点错了',
						showClose: false,
						closeOnClickModal: false
					})
					.then(() => {
						self.$refs[formName].resetFields();
						self.releaseForm.type = '';
						self.project_id = '';
						self.direction_val = '';
						self.releaseForm.addresses = [];
						self.releaseForm.uuid = [];
					})
					.catch(() => {});
			},
			// 复制链接
			copyVersionLink(row) {
				console.log(row)
			},
			// 上传
			// 移除文件
			removeVersion() {
				let self = this;
				self.isPercentage = false;
				self.percentage = 0;
			},
			// 上传之前
			beforeVersion(file) {
				let self = this;
				self.versionFile = file;
				self.versionName = md5(file.name);
				self.suffix = file.name.substring(file.name.lastIndexOf('.') + 1);
				self.versionFileName = `${self.versionName}.${self.suffix}`;
			},
			// 上传成功
			successVersion() {
				let self = this;
				self.$message.success("上传版本成功");
			},
			// 进度条
			versionProcess(event) {
				let self = this;
				self.isPercentage = true;
				self.percentage = (event.loaded / event.total * 100 | 0);
			},
			// 只能上传一个
			onlyVersion() {
				let self = this;
				self.$message.error('只能上传一个文件');
			},
			// 点击上传文件
			versionUpload() {
				let self = this;
				self.$refs.uploadVersion.submit();
				self.$message.success('正在上传文件，请稍后');
				self.loading = true;
				let cos = new COS({
					getAuthorization(options, callback) {
						callback({
							TmpSecretId: self.uploadSign.Credentials.TmpSecretId,
							TmpSecretKey: self.uploadSign.Credentials.TmpSecretKey,
							SecurityToken: self.uploadSign.Credentials.Token,
							ExpiredTime: self.uploadSign.ExpiredTime
						});
					}
				});
				cos.putObject({
					Bucket: 'anyuchuzuwu-1301548258',
					Region: 'ap-guangzhou',
					Key: 'firemare/' + self.versionFileName,
					StorageClass: 'STANDARD',
					Body: self.versionFile, // 上传文件对象
				}, function(err, data) {
					if (err) {
						self.loading = false;
						self.$message.warning('上传失败');
					}
					self.$message.success('上传成功');
					self.loading = false;
					self.form.href = data.Location;
				})
			},
			// 获取上传token
			getUploadToken() {
				let self = this;
				API.cosToken().then(res => {
					self.uploadSign = res.data;
				})
			}
		}
	}
</script>

<style scoped lang="scss">
	.table-box {
		margin: 10px 0;
	}

	.m-pagination {
		padding: 20px 0;
		text-align: center;
	}

	.m-form {
		margin: 20px;
		padding-bottom: 200px;
	}

	.u-drawer-title {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px;
		font-size: 24px;
	}

	/deep/ .el-transfer-panel {
		width: 400px;
	}
</style>
